package com.university.mentalhealthplatform.studentV3.ai.message;

import cn.hutool.core.collection.CollectionUtil;
import com.university.mentalhealthplatform.studentV3.ai.session.AiSession;
import io.qifan.infrastructure.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.*;
import org.springframework.ai.model.Media;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Repository
@AllArgsConstructor
public class AiMessageChatMemory implements ChatMemory {

    private final AiMessageRepository aiMessageRepository;

    @Override
    public void add(String conversationId, List<Message> messages) {
        List<AiMessageImpl> aiMessages = messages.stream().map(message -> {
            AiMessageImpl aiMessage = new AiMessageImpl();
            aiMessage.setSession(new AiSession(conversationId));
            aiMessage.setCreatedTime(LocalDateTime.now());
            aiMessage.setEditedTime(LocalDateTime.now());
            aiMessage.setCreatorId("system"); // 设置创建者ID
            aiMessage.setEditorId("system"); // 设置编辑者ID

            if (message instanceof UserMessage) {
                aiMessage.setType("USER");
                aiMessage.setTextContent(message.getContent());
            } else if (message instanceof AssistantMessage) {
                aiMessage.setType("ASSISTANT");
                aiMessage.setTextContent(message.getContent());
            } else if (message instanceof SystemMessage) {
                aiMessage.setType("SYSTEM");
                aiMessage.setTextContent(message.getContent());
            } else {
                throw new BusinessException("Unsupported message type");
            }

            return aiMessage;
        }).collect(Collectors.toList());

        aiMessageRepository.saveAll(aiMessages);
    }

    @Override
    @Transactional
    public List<Message> get(String conversationId, int lastN) {
        return aiMessageRepository.findBySessionId(conversationId)
                .stream()
                .limit(lastN)
                .map(AiMessageChatMemory::toSpringAiMessage)
                .collect(Collectors.toList());
    }

    @Override
    public void clear(String conversationId) {
        aiMessageRepository.deleteBySessionId(conversationId);
    }

    @SneakyThrows
    public static Message toSpringAiMessage(AiMessage aiMessage) {
        List<Media> mediaList = new ArrayList<>();

        String type = aiMessage.getType();
        if (type == null) {
            throw new IllegalArgumentException("Message type cannot be null");
        }

        switch (type) {
            case "ASSISTANT":
                return new AssistantMessage(aiMessage.getTextContent());
            case "USER":
                return new UserMessage(aiMessage.getTextContent(), mediaList);
            case "SYSTEM":
                return new SystemMessage(aiMessage.getTextContent());
            default:
                throw new BusinessException("不支持的消息类型");
        }
    }

}